package com.example.rtspDemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@RequestMapping("/rtsp")
public class RtspController {

    @Autowired
    private WsHandler wsHandler;

    @Autowired
    private ConvertVideoPacket convertVideoPacket;

    @RequestMapping("/receive/{id}")
    @ResponseBody
    public void receive(HttpServletRequest request, Object response,@PathVariable("id") Long id ){
        ServletInputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            int len = -1;
            while ((len =inputStream.available()) !=-1) {
                byte[] data = new byte[len];
                inputStream.read(data);

                wsHandler.sendVideo(data,id);
            }
        } catch (Exception e) {
           // e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("over");
    }

    @RequestMapping("/toPlay")
    @ResponseBody
    public String toPlay(Long id) {
        if(WsHandler.clients.containsKey(id)){
            return "ws://127.0.0.1:8081/aa/"+id;
        }
        if(id==1){
            new Thread(){
                public  void run(){
                    wsHandler.clients.put(id,new ConcurrentHashMap<>());
                    convertVideoPacket.pushVideoAsRTSP("rtsp://admin:ch123456@192.168.1.108:554/cam/realmonitor?channel=1&amp;subtype=0", "http://127.0.0.1:8081/rtsp/receive/"+id,id);
                }
            }.start();
        }else{
            new Thread(){
                public  void run(){
                    wsHandler.clients.put(id,new ConcurrentHashMap<>());
                    convertVideoPacket.pushVideoAsRTSP("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov", "http://127.0.0.1:8081/rtsp/receive/"+id,id);
                }
            }.start();

        }
        return "ws://127.0.0.1:8081/aa/"+id;
    }

}
